<?php
namespace App\Http\Controllers\Logic;
use App\Helpers\ProjectHelper;
use App\Http\Controllers\Constant\Constant;
use App\Http\Controllers\Controller;
use App\Model\OAAdmin;
use App\Model\OACompany;
use App\Model\OADept;
use App\Model\OAFiles;
use App\Model\OAFinance;
use App\Model\OAPartners;
use App\Model\OAPosition;
use App\Model\OAPositionMapping;
use App\Model\OAProjectLx;
use App\Model\OAProjectYs;
use App\Model\OAProjectYsDetail;
use App\Model\OAShenPiLog;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * 立项
 */
class ProjectLogic extends Controller
{
    protected static $work_id = 1;

    protected $status_list = ['备审','待审','已审'];

    public function addNewProject($params)
    {
        DB::beginTransaction();
        try{
            $filed_list = Schema::getColumnListing('project_lx');
            $project = new OAProjectLx();
            array_push($filed_list,'xmid');
           if(strtotime($params['start']) >= strtotime($params['stop'])) throw new \Exception('开始时间不能大于结束时间');
            foreach ($params as $key => &$val){
                if(!in_array($key,$filed_list)) unset($params[$key]);
                if(in_array($key,['offer','cost'])) $val = resetMoney($val);
            }
            $cost = Arr::get($params,'cost',0);
            $offer = Arr::get($params,'offer',0);
            //dd($cost,$offer);
            if($cost < 1) throw new \Exception("项目成本不能为空");
            if($offer < 1) throw new \Exception("客户报价不能为空");
            $params['batch_id'] = $this->generateBatchId($params['gsid'],$params['deptid']);
            $process = ProjectHelper::getRolesAndUidsByWorkIdAndGsId(self::$work_id,Arr::get($params,'gsid'));
            $params['create_role'] = roleid();
            $params['node_id'] = $this->getCurrentNode(self::$work_id);
            $params['work_id'] = self::$work_id;
            $is_save = $params['is_save'];
            $params['roleid'] = $params['create_role'];
            $params['status'] = 0;
            $params = array_merge($process,$params);
            //dd(11);
            //0:提交1:保存
            if(!$is_save){
                //提交
                $nextApprover = $this->getNextApprover($params['node_id'],self::$work_id,Constant::PROJECT_STATUS_WAIT);
                $params['roleid'] = $nextApprover['roleid'];
                $params['node_id'] = $nextApprover['node_id'];
                $params['status'] = Arr::get($nextApprover,'status');
            }
            //dd($params);
            if($xmid = Arr::get($params,'xmid')){
                $lx = OAProjectLx::query()->find($xmid);
                $lx->fill($params)->save();
                $id = $lx->id;
            }else{
                $lx = OAProjectLx::query()->create($params);
                $id = $lx->id;
            }
            if(!$is_save){
                $note = sprintf("创建立项%s",Arr::get($params,'name'));
                OAShenPiLog::createShenPiLogs(self::$work_id,$id,$note,OAShenPiLog::SHENPI_STATUS_PASS);
            }
            DB::commit();
            return $id;
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    //获取立项数据
    public function getProjectLx($params)
    {
        //dd($params);
        DB::enableQueryLog();
        try {
            $query = OAProjectLx::createQueryBuilder($params);
            $list = $query->paginate($params['page_size'], [
                'id',
                'name',
                'uid',
                'leader',
                'batch_id',
                'offer',
                'cost',
                'currency',
                'start',
                'stop',
            ], 'page')
                ->toArray();
            if ($list['data']) {
                foreach ($list['data'] as &$val) {
                    $val['offer'] = fomateMoney($val['currency'], $val['offer']);
                    $val['cost'] = fomateMoney($val['currency'], $val['cost']);
                    $val['date'] = $val['start'] . '-' .$val['stop'];
                    unset($val['currency']);
                }
            }
            $list['status_list'] = $this->status_list;
            return $list;

        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }

    }

    //项目详情
    public function projectDetailLx($params)
    {
        try{
            $project_info = OAProjectLx::query()->find(Arr::get($params,'id'));
            $logic = new ApproveHistory();
            $project_info->history = $logic->getApproveHistory($project_info);
            $project_info->deptName = $project_info->dept_name;
            $project_info->companyName = $project_info->company_name;
            $project_info->spForm = OAShenPiLog::getTempSpFormData($project_info->work_id,$project_info->id);
            return $project_info;
        }catch (\Exception $e){
            throw new \Exception($e->getMessage() . ' on line '.$e->getLine());
        }
    }

    //编辑项目数据
    public function editProjectLx($params, OAProjectLx $project)
    {
        //dd($params);
        DB::beginTransaction();
        try{
            if(strtotime($params['start']) < strtotime($params['created_at'])) throw new \Exception('开始时间不能大于立项时间');
            if(strtotime($params['stop']) < strtotime($params['created_at'])) throw new \Exception('结束时间不能大于立项时间');
            if(strtotime($params['start']) > strtotime($params['stop'])) throw new \Exception('开始时间不能大于结束时间');

            if(!validateMobile($params['leader_mobile'])) throw new \Exception('项目电话格式错误');
            if(!validateMobile($params['seller_mobile'])) throw new \Exception('销售电话格式错误');
            if(!validateMobile($params['customer_mobile'])) throw new \Exception('客户电话格式错误');

            //1.查新旧数据,写日志
            $log = $this->checkDifferentData($params,'lx');
            if($log){
                OAShenPiLog::createShenPiLogs(self::$work_id,$params['id'],$log,OAShenPiLog::SHENPI_STATUS_LOG);
            }else{
                $isExists = OAShenPiLog::checkShenLogExists(self::$work_id,Arr::get($params,'id'));
                if(isPM() && !$isExists && !Arr::get($params,'is_save')){
                    OAShenPiLog::createShenPiLogs(self::$work_id,$project->id,sprintf('创建立项%s',Arr::get($params,'name')),OAShenPiLog::SHENPI_STATUS_PASS);
                }
            }
            #2.修改数据
            $project->name = $params['name'];
            $project->gsid = $params['gsid'];
            $project->leader = $params['leader'];
            $project->leader_mobile = $params['leader_mobile'];
            $project->seller = $params['seller'];
            $project->seller_mobile = $params['seller_mobile'];
            $project->customer = $params['customer'];
            $project->customer_mobile = $params['customer_mobile'];
            $project->currency = $params['currency'];
            $project->offer = resetMoney($params['offer']);
            $project->cost = resetMoney($params['cost']);
            $project->desc = $params['desc'];
            $project->start = $params['start'];
            $project->stop = $params['stop'];
            $project->is_save = $params['is_save'];
            $project->city = $params['city'];
            $project->created_at = date('Y-m-d 00:00:00',strtotime($params['created_at']));
            //是否是创建人
            $isCreateUser = $project->uid == $params['uid'];
            if(!$params['is_save'] && $isCreateUser){
                $nextApprover = $this->getNextApprover($project->node_id,self::$work_id,Constant::PROJECT_STATUS_WAIT);
                $project->node_id = $nextApprover['node_id'];
                $project->roleid = $nextApprover['roleid'];
                $project->deptid = $params['deptid'];
                $project->status = Arr::get($nextApprover,'status');
            }
            //修改公司审批人员
            if($project->gsid != $params['gsid']){
                $project->approver = $this->getRoleMapCompany(self::$work_id,$params['gsid']);
            }
            $project->save();
            //审批日志保存
            $note = Arr::get($params,'spForm.note','');
            if($note){
                OAShenPiLog::createShenPiLogs(self::$work_id,$project->id,$note,OAShenPiLog::SHENPI_STATUS_NOTHING);
            }
            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    //修改客户名称
    public function editProjectPartner($params)
    {
       return OAProjectLx::query()->where('id',$params['id'])->update(['partner_id'=>$params['partner_id']]);
    }

    //获取预算下拉列表
    public function getYsList($params){
        $list =  OAProjectLx::query()->where([
            'create_role'=>$params['roleid'],
            'status'=>Constant::PROJECT_STATUS_COMPLETED,
            'uid'=>$params['uid'],
            'deptid'=>$params['deptid']
            ])
            ->orderBy('updated_at','DESC')
            ->select(['id','name'])
            ->get()
            ->toArray();

        foreach ($list as $k => $item){
            $isExists = OAProjectYs::query()->where(['xmid'=>$item['id'],'type'=>1])->exists();
            if($isExists) unset($list[$k]);
        }

        return $list;
    }

    //删除项目
    public function delProject($params)
    {
        try {
            DB::beginTransaction();
            $type = $params['type'];
            $id = $params['id'];
            $roleid = roleid();
            $params['isAdmin'] = $this->isAdmin($roleid);
            $uid = admin_id();
            $checkProject = function ($project,$roleid) use($uid){
                if(is_null($project)) throw new \Exception('项目不存在');
                $mapPosition = OAPositionMapping::getPositionMapping($project->roleid);
                $mapPosition[] = OAPosition::ROLE_ADMIN;
                if($roleid != $project->create_role) throw new \Exception("职位无权限");
                if(!in_array($roleid,$mapPosition)) throw new \Exception('当前项目正在审批');
                if($project->uid != $uid) throw new \Exception('当前仅立项人可删除');
            };
            switch ($type) {
                case 'lx':
                    $project = OAProjectLx::query()->find($id);
                    $checkProject($project,$roleid);
                    $ysList = $project->ys;
                    if($ysList){
                        $ysList->each(function($ys){
                            if($ys->status == Constant::PROJECT_STATUS_WAIT) throw new \Exception('当前项目正在审批');
                            $ys->delete();
                            $ys->ysDetail()->delete();
                        });
                    }
                    $cwList = $project->cw;
                    if($cwList){
                        $cwList->each(function($cw){
                            if($cw->status == Constant::PROJECT_STATUS_WAIT) throw new \Exception('当前项目正在审批');
                            $cw->delete();
                            $cw->clvs()->delete();
                        });
                    }
                    $project->delete();
                    break;
                case 'ys':
                    $project = OAProjectYs::query()->find($id);
                    //dd($project);
                    $checkProject($project,$roleid);
                    $lx = $project->projectLx;
                    $cwList = $lx->cw;
                    if($cwList){
                        $cwList->each(function($cw){
                            if($cw->status == Constant::PROJECT_STATUS_WAIT) throw new \Exception('当前项目正在审批');
                            $cw->delete();
                            $cw->clvs()->delete();
                        });
                    }
                    $project->ysDetail()->delete();
                    $project->delete();
                    break;

                case 'js':
                    $project = OAProjectYs::query()->find($id);
                    $checkProject($project,$roleid);
                    $project->delete();
                    break;
                case 'cw':
                    $project = OAFinance::query()->find($id);
                    $checkProject($project,$roleid);
                    $project->delete();
                    break;
                case 'xz':
                    $project = OAAdmin::query()->find($id);
                    $checkProject($project,$roleid);
                    $project->delete();
                    break;
            }

            DB::commit();
            return true;

        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

    //删除审批日志
    protected function delShenPiLog($params)
    {
        $where = ['pid'=>$params['pid'],'work_id'=>$params['work_id']];
        return OAShenPiLog::query()->where($where)->delete();
    }

    //删除附件
    public function delFiles($params)
    {
        $where = ['pid'=>$params['pid'],'type'=>$params['type']];
        if(array_key_exists('id',$params)) $where = ['id'=>$params['id']];
        return OAFiles::query()->where($where)->delete();
    }

}


